package com.runrunfast.face.service.common;

import com.runrunfast.face.util.YoutuProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 优图API Service
 *
 * @author YangNing
 */
@Service
public class YoutuService {

    private static Logger logger = LoggerFactory.getLogger(YoutuService.class);

    @Autowired
    private YoutuProperties youtu;

    /**
     * 初始化携带鉴权信息Header信息的请求数据
     *
     * @param requestParams
     * @param apiPath
     * @param method
     * @return
     */
    public HttpEntity initJsonEntity(Object requestParams, String apiPath, HttpMethod method) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", getAuthorization(apiPath, method));
        headers.add("X-Request-Id", "123456789");
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        return new HttpEntity<>(requestParams, headers);
    }

    /**
     * 初始化携带鉴权信息Header信息的请求数据
     *
     * @param requestParams
     * @param apiPath
     * @param method
     * @return
     */
    public HttpEntity initFileEntity(Object requestParams, String apiPath, HttpMethod method) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", getAuthorization(apiPath, method));
        headers.add("X-Request-Id", "123456789");
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        return new HttpEntity<>(requestParams, headers);
    }

    /**
     * 初始化携带鉴权信息Header信息的请求数据
     *
     * @param requestParams
     * @param apiPath
     * @param method
     * @return
     */
    public HttpEntity initEntity(Object requestParams, String apiPath, HttpMethod method) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", getAuthorization(apiPath, method));
        headers.add("X-Request-Id", "123456789");
        return new HttpEntity<>(requestParams, headers);
    }

    /**
     * 生成请求头Authorization参数
     *
     * @param apiPath
     * @param method
     * @return
     */
    public String getAuthorization(String apiPath, HttpMethod method) {
        long timestamp = System.currentTimeMillis() / 1000;
        String signature = getSignature(apiPath, method, timestamp);
        String authorization = "dk=" + youtu.getDevKey() + "&ak=" + youtu.getSecretId() + "&st=" + timestamp + "&sign=" + signature;
        logger.info("Authorization---->: " + authorization);
        return authorization;
    }

    /**
     * 生成签名串
     *
     * @param apiPath
     * @param method
     * @param timestamp
     * @return
     */
    private String getSignature(String apiPath, HttpMethod method, long timestamp) {
        String content = youtu.getDevKey()
                + method.toString().toLowerCase()
                + apiPath
                + youtu.getSecretId()
                + youtu.getSecretKey()
                + timestamp;
        String signature = encrypt(content, "SHA-256");
        return signature;
    }

    private String encrypt(String strSrc, String encName) {
        MessageDigest md;
        String strDes;
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance(encName);
            md.update(bt);
            strDes = bytes2Hex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            logger.info("加密失败！");
            return null;
        }
        return strDes;
    }

    private String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }
}
